<?php
	mysql_connect("localhost", "root", "%Tg34fv1", true)or die("cannot connect");
	mysql_select_db("wordWaffle") or die("cannot select DB");

	$myKey = mysql_real_escape_string(stripslashes($_GET['sesskey']));
	//validate sesskey
	$result=mysql_query("SELECT * FROM players WHERE sesskey=$myKey");
	$count=mysql_num_rows($result);
	if ($count==0) 
	{	//unrecognized session key!
		echo "Unrecognized session key!";
		return;
	}
	
	//ensure there was a game being played
	$playerList=mysql_query("SELECT * FROM players");
	$playerCount = mysql_num_rows($playerList);
	if ($playerCount == 0)
	{
		echo "No game to score.";
		return;
	}
	
	//ensure all letters have been placed
	$w=mysql_query("SELECT * FROM waffle ORDER BY sesskey, x, y");
	if (( $playerCount * 25) != mysql_num_rows($w))
	{
		echo "Game is not yet finished.";
	 	return;
	}
	
	//create list of all possible words for each player
	while ($playerRow = mysql_fetch_assoc($playerList))
	{
		$thisKey = $playerRow['sesskey'];
		$myGrid = mysql_query("SELECT * FROM waffle WHERE sesskey=$thisKey");
		while ($row = mysql_fetch_assoc($myGrid))
			$waffle[$row['x']][$row['y']] = $row['letter'];
				
		//five letter words
		for ($i=1;$i<=5;$i++)
		{
			$wordAcross = "";
			$wordDown = "";
			for ($j=1;$j<=5;$j++)
			{
				$wordAcross .= $waffle[$i][$j];
				$wordDown .= $waffle[$j][$i];
			}
			mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordAcross', 10)");
			mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordDown', 10)");
		}
		
		//four letter words
		for ($i=1;$i<=5;$i++)
			for ($k=0;$k<=1;$k++)
			{
				$wordAcross = "";
				for ($j=1+$k;$j<=4+$k;$j++)
					$wordAcross .= $waffle[$i][$j];
				mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordAcross', 5)");
				
			}
		for ($i=1;$i<=5;$i++)
			for ($k=0;$k<=1;$k++)
			{
				$wordDown = "";
				for ($j=1+$k;$j<=4+$k;$j++)
					$wordDown .= $waffle[$j][$i];
				mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordDown', 5)");			
			}

		//three letter words
		for ($i=1;$i<=5;$i++)
			for ($k=0;$k<=2;$k++)
			{
				$wordAcross = "";
				for ($j=1+$k;$j<=3+$k;$j++)
					$wordAcross .= $waffle[$i][$j];
				mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordAcross', 1)");
			}
		for ($i=1;$i<=5;$i++)
			for ($k=0;$k<=2;$k++)
			{
				$wordDown = "";
				for ($j=1+$k;$j<=3+$k;$j++)
					$wordDown .= $waffle[$j][$i];
				mysql_query("INSERT INTO allWords VALUES ($thisKey, '$wordDown', 1)");			
			}
	}
	
	//now query for only actual words
	mysql_query("UPDATE allWords LEFT JOIN wordlist ON allWords.word=wordlist.word SET allWords.word='x' WHERE wordlist.word IS NULL");
	mysql_query("DELETE FROM allWords WHERE word='x'");
	mysql_query("UPDATE players SET readyToPlay=0");
	return;	
?>